﻿#include "ScreenshotTool.h"

ScreenshotTool::ScreenshotTool(QWidget *parent) : QMainWindow(parent), m_screenshotOverlay(nullptr)
{
    setWindowTitle("截图工具");
    resize(400, 300);
}

void ScreenshotTool::takeScreenshot()
{
    if (m_screenshotOverlay) {
        m_screenshotOverlay->deleteLater();
        m_screenshotOverlay = nullptr;
    }

    m_screenshotOverlay = new ScreenshotOverlay();
    connect(m_screenshotOverlay, &ScreenshotOverlay::accepted, this, &ScreenshotTool::onScreenshotAccepted);
    connect(m_screenshotOverlay, &ScreenshotOverlay::cancelled, this, &ScreenshotTool::onScreenshotCancelled);
    connect(m_screenshotOverlay, &ScreenshotOverlay::saveRequested, this, &ScreenshotTool::onScreenshotSaveRequested);

    m_screenshotOverlay->show();
}

void ScreenshotTool::onScreenshotAccepted(const QPixmap &screenshot)
{
    // 先关闭截图窗口
    closeScreenshotOverlay();

    // 将截图复制到剪贴板
    QApplication::clipboard()->setPixmap(screenshot);

    // 使用定时器延迟显示消息框，确保截图窗口已完全关闭
    QTimer::singleShot(100, this, [this]() {
        QMessageBox::information(this, "截图完成", "截图已复制到剪贴板");
    });
    emit sigShowMainwindow();
}

void ScreenshotTool::onScreenshotCancelled()
{
    // 关闭截图窗口
    closeScreenshotOverlay();
    emit sigShowMainwindow();
}

void ScreenshotTool::onScreenshotSaveRequested(const QPixmap &screenshot)
{
    // 先关闭截图窗口
    closeScreenshotOverlay();

    // 使用定时器延迟显示文件对话框，确保截图窗口已完全关闭
    QTimer::singleShot(100, this, [this, screenshot]() {
        QString fileName = QFileDialog::getSaveFileName(
            this,
            "保存截图",
            QString("%1/截图_%2.png")
                .arg(QStandardPaths::writableLocation(QStandardPaths::PicturesLocation))
                .arg(QDateTime::currentDateTime().toString("yyyyMMdd_hhmmss")),
            "PNG图像 (*.png);;JPEG图像 (*.jpg *.jpeg);;BMP图像 (*.bmp)"
            );

        if (!fileName.isEmpty()) {
            if (screenshot.save(fileName)) {
                QMessageBox::information(this, "保存成功", "截图已保存");
            } else {
                QMessageBox::warning(this, "保存失败", "无法保存截图");
            }
        }
    });
    emit sigShowMainwindow();
}

void ScreenshotTool::closeScreenshotOverlay()
{
    if (m_screenshotOverlay) {
        // 先断开所有连接，防止信号重复触发
        disconnect(m_screenshotOverlay, 0, this, 0);

        // 隐藏窗口
        m_screenshotOverlay->hide();

        // 延迟删除，确保事件处理完成
        QTimer::singleShot(0, m_screenshotOverlay, &QObject::deleteLater);
        m_screenshotOverlay = nullptr;
    }
}
